<template>
  <div class="div1">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>添加产品</span>
        </div>
      </template>
      <el-form
        label-position="top"
        ref="ruleFormRef"
        :model="newsForm"
        :rules="rules"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="产品名称" prop="title">
          <el-input v-model="newsForm.title" />
        </el-form-item>

        <el-form-item label="产品简要描述" prop="introduction">
          <el-input v-model="newsForm.introduction" />
        </el-form-item>

        <el-form-item label="产品详细描述" prop="detail">
          <el-input v-model="newsForm.detail" type="textarea" />
        </el-form-item>

        <el-form-item label="封面" prop="file">
          <upload @uploadimg="uploadimg" />
        </el-form-item>
        <el-form-item>
          <el-button v-if="!Editdata" @click="Productadd" type="primary">
            添加
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import upload from "../New-manager/upload.vue";
import dayjs from "dayjs";
import { AddProduct } from "@/request/home/userapi.js";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted, watch, computed } from "vue";
const newsForm = reactive({
  title: "",
  introduction: "",
  detail: "",
  cover: 0,
  file: null,
});
const props = defineProps({
  Editdata: "",
});

function handldercontent(value) {
  newsForm.content = value;
}
function uploadimg(value) {
  newsForm.file = value;
  console.log(newsForm.file);
}
const ruleFormRef = ref();
const validatePass = (rule, value, callback) => {
  if (newsForm.introduction === "") {
    callback(new Error("产品简要描述"));
  } else callback();
};
const rules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  introduction: [{ required: true, validator: validatePass, trigger: "blur" }],
  detail: [{ required: true, message: "产品详细描述", trigger: "blur" }],
  file: [{ required: true, message: "请插入图片", trigger: "blur" }],
});
const Productadd = () => {
  ruleFormRef.value.validate(async (test) => {
    if (test) {
      const params = new FormData();
      Object.keys(newsForm).forEach((i) => {
        params.append(i, newsForm[i]);
      });

      const result = await AddProduct(params);
      if (result.data.code === 200) {
        ElMessage({
          message: result.data.msg,
          type: "success",
        });
      } else {
        ElMessage({
          message: result.data.msg,
          type: "error",
        });
      }
    }
  });
};
</script>

<style scoped>
.div1 {
  background: rgb(255, 255, 255);
  width: 100%;
}

.box-card {
  width: 100%;
}
</style>